package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.member.MemberRespTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SeckillSkuVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceimpl implements SeckillService {


    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//加上商品随机码

    @Override
    public void uploadSeckillSkuLatest3Day() {
        List<SeckillSessionsWithSkus> sessionData;
        R r = couponFeignService.getSKuLatest3Day();
        if (r.getCode() == 0) {
            //成功
            sessionData = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });

            //缓存信息
            //1.缓存活动信息
            //2.缓存关联的商品信息
            saveSessionInfos(sessionData);
            saveSessionSkuInfo(sessionData);
        }
    }


    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();

            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;

            Boolean isExt = redisTemplate.hasKey(key);
            if (!isExt) {
                List<String> skuIds = session.getRelationSkus().stream().map(item -> {
                    //TODO 老师的是item.getId()
                    return item.getPromotionSessionId() + "_" + item.getSkuId().toString();
                }).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, skuIds);
            }


        });
    }

    private void saveSessionSkuInfo(List<SeckillSessionsWithSkus> sessionData) {
        //准备hash操作
        BoundHashOperations ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        sessionData.stream().forEach(session -> {
                    session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        String token = UUID.randomUUID().toString().replace("_", "");
                        if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())) {
                            //缓存商品
                            //1.sku的基本信息
                            BeanUtils.copyProperties(seckillSkuVo, redisTo);
                            //2.sku的秒杀信息
                            R r = productFeignService.getSKuInfo(seckillSkuVo.getSkuId());
                            if (r.getCode() == 0) {
                                SkuInfoVo skuInfoVo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                                });
                                redisTo.setSkuInfo(skuInfoVo);
                            }
                            //3.保存随机码，结束时间
                            redisTo.setStartTime(session.getStartTime().getTime());
                            redisTo.setEndTime(session.getEndTime().getTime());

                            redisTo.setRandomCode(token);

                            String s = JSON.toJSONString(redisTo);
                            ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), s);

                            //5.使用Redisson限流(RSemaphore)
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                            semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                        }
                    });
                }
        );

    }

    //Ajax获取当前秒杀时间的商品
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        Date date = new Date();
        long time = date.getTime();

        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");

            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);

            if (time >= start && time <= end) {
                //当前场次
                //2.获取当前场次的需要的信息
                List range = redisTemplate.opsForList().range(key, -100, +100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<Object> list = hashOps.multiGet(range);
                if (list != null && list.size() > 0) {
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        SeckillSkuRedisTo redisTo = JSON.parseObject(item.toString(), SeckillSkuRedisTo.class);
//                        redisTo.setRandomCode();
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTo getSeckillSkusInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String reg = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(reg, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    //随机码
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    if (System.currentTimeMillis() >= startTime && System.currentTimeMillis() <= endTime) {
                        //不做处理
                    } else {
                        //随机码置空
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
                ;
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespTo memberRespTo = LoginInterceptor.threadLocal.get();
        //1.获取当前商品的秒杀信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //合法性校验
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            Long now = System.currentTimeMillis();
            //1.校验时间的合法性
            if (now > startTime && now < endTime) {
                //在秒杀时间内
                //2.校验随机码
                String randomCode = redisTo.getRandomCode();
                String id = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                if (randomCode.equals(key) && id.equals(killId)) {
                    //数据合法
                    //3.验证购物数量是否合理
                    if (num <= redisTo.getSeckillLimit()) {
                        //4.验证这个商品是否购买过
                        String redisKey = memberRespTo.getId() + "_" + redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                        //自动过期,
                        Long ttl = endTime - now;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功过，之前没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);

                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                //秒杀成功
                                //快速下单
                                String timeId = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setMemberId(memberRespTo.getId());
                                orderTo.setOrderSn(timeId);//订单号
                                orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());//设置活动id
                                orderTo.setNum(num);
                                orderTo.setSkuId(redisTo.getSkuId());
                                orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                                return timeId;
                            }
                            return null;

                        } else {
                            //占位失败，返回为空
                            return null;
                        }

                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }
        return null;
    }
}
